package com.aooci.ordercat.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.aooci.ordercat.dao.AbstractBaseDAO;

/**
 * Abstract Base DAO that contains a number of base methods that can be used for each entity
 */
public class AbstractBaseDAOImpl<T, K extends Serializable> extends HibernateDaoSupport implements AbstractBaseDAO<T, K>{

	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(AbstractBaseDAOImpl.class);
	private Class<T> clazz;

	/**
	 * the default constructor that takes a class of the entity
	 * @param clazz the class of the entity
	 */
	public AbstractBaseDAOImpl(Class<T> clazz){
		this.clazz = clazz;
	}
	
	@Override
	public List<T> findAll() {
		return getHibernateTemplate().loadAll(clazz);
	}

	@Override
	public void save(T entity) {
		try {
			getHibernateTemplate().saveOrUpdate(entity);
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	@Override
	public void delete(T entity) {
		try {
			getHibernateTemplate().delete(entity);
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	@Override
	public T findById(K id) {
		try {
			return getHibernateTemplate().get(clazz, id);
		} catch (RuntimeException re) {
			log.error("findById failed", re);
			throw re;
		}
	}
}